package com.zld.smarket.controller;

import com.zld.smarket.pojo.Goods;
import com.zld.smarket.pojo.Goodsloss;
import com.zld.smarket.pojo.Stock;
import com.zld.smarket.result.ExceptionMsg;
import com.zld.smarket.result.ResponseData;
import com.zld.smarket.service.GoodsLossService;
import com.zld.smarket.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/loss")
public class GoodsLossController {
    @Autowired
    private GoodsLossService goodsLossService;

    @Autowired
    private StockService stockSerinvice;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ResponseData findList(Integer page, Integer limit){
        return  goodsLossService.findList(page,limit);
    }

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public ResponseData search(String s,Integer page, Integer limit){
        return  goodsLossService.search(s,page,limit);
    }

    @RequestMapping(value = "/weekloss",method = RequestMethod.GET)
    public Long weekloss(String s,Integer page, Integer limit){
        return  goodsLossService.totalloss();
    }



    @RequestMapping(value = "/setLoss")
    public ResponseData add(Goodsloss goodsloss){
        Long i=goodsloss.getLossNo();
        if(goodsLossService.selectbyno(i)>0){
            return new ResponseData(ExceptionMsg.ADDERROR);
        }else {
            goodsloss.setLossDate(new Date());
            List<Stock> stocks =stockSerinvice.selectbyGoodsno(goodsloss.getGoodsNo(),goodsloss.getSupplierId(),goodsloss.getStorehouseNo());
            if(stocks.size()==1){
                if(stocks.get(0).getStockNum()<goodsloss.getLossNum()){
                    return new ResponseData(ExceptionMsg.OUTOFNUM);
                }else {
                    Integer integer1 =stockSerinvice.reduceStockNum(goodsloss.getGoodsNo(),goodsloss.getSupplierId(),goodsloss.getStorehouseNo(),goodsloss.getLossNum());
                    Integer integer = goodsLossService.setloss(goodsloss);
                    return new ResponseData(ExceptionMsg.SUCCESS);
                }
            }else {
                return new ResponseData(ExceptionMsg.EMPTY);
            }

        }
    }
}
